﻿using System;
using System.Reflection;
using Codeflows.Dispatch;
using Codeflows.Tracking;

namespace Codeflows
{
    class ActionContext : IActionContext
    {
        public static readonly MethodInfo ArgumentResolver = typeof(ActionContext).GetMethod("ResolveArgument", 
            BindingFlags.Instance | BindingFlags.NonPublic);

        readonly CodeflowInstance _codeflowInstance;

        public ActionContext(CodeflowInstance codeflowInstance)
        {
            if (codeflowInstance == null) throw new ArgumentNullException("codeflowInstance");

            _codeflowInstance = codeflowInstance;            
        }

        protected object ResolveArgument(string name, string type)
        {
            if (type == typeof(IActionContext).AssemblyQualifiedName)
                return this;

            object value;
            if (!_codeflowInstance.CurrentAction.Arguments.TryGetValue(name, out value))
                throw new InvalidOperationException("Could not find the required argument - " + name);

            return value;
        }

        public int DispatchAttemptsCount
        {
            get { return _codeflowInstance.CurrentAction.DispatchAttemptsCount; }
        }

        public Guid CodeflowId
        {
            get { return _codeflowInstance.CodeflowId; }
        }
    }
}
